package com.jinsilu.freight.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.view.SwitchButton;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.InputTextHelper;
import com.jinsilu.freight.helper.ReplaceHelper;
import com.jinsilu.freight.helper.ShowImageHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.AddBankInfoApi;
import com.jinsilu.freight.http.request.EditBankInfoApi;
import com.jinsilu.freight.http.request.GetUserInfoApi;
import com.jinsilu.freight.http.request.UpdateImageApi;
import com.jinsilu.freight.http.response.BankDetailsBean;
import com.jinsilu.freight.http.response.BankInfoBean;
import com.jinsilu.freight.http.response.DictBean;
import com.jinsilu.freight.http.response.FileBean;
import com.jinsilu.freight.http.response.IdCardBean;
import com.jinsilu.freight.http.response.UserInfoBean;
import com.jinsilu.freight.other.MTLConstants;

import java.io.File;

/**
 * 添加银行卡页面
 *
 * @author yangyang
 * @time 2020-11-10 17:15
 */
public class MyBankEditActivity extends MyActivity {

    private EditText mUserName;
    private EditText mUserIDCard;
    private EditText mBankCard;
    private TextView mBankCardName;
    private TextView mBtnSubmit;
    private SwitchButton mSwitchBtn;

    // Add new fields for recipient information
    private EditText mRecipientPhone;
    private LinearLayout layoutRecipientInfo;
    private LinearLayout layoutRecipientPhotos;
    private ImageView mIvIdCardFront;
    private ImageView mIvIdCardBack;
    private TextView mTvIdCardFrontTips;
    private TextView mTvIdCardBackTips;

    private LinearLayout layoutBankInfo;
    private LinearLayout layoutCardUserName;
    private LinearLayout layoutCardIdCard;

    private String mCardNumber;
    private String mUserOwnIdCard; // 用户自己的身份证号
    private String mFrontImage; // 身份证正面照片URL
    private String mBackImage; // 身份证反面照片URL
    private int mCurrentSelectIndex; // 当前选择上传的图片索引

    private Handler handler = new Handler();

    private DictBean dictBean;
    private int isDefault = MTLConstants.IS_NOT_DEFAULT; // 默认标识（1非默认；0默认)

    BankInfoBean bankInfoBean;

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            // 在这里调用服务器的接口，获取数据
            // if (mCardNumber.length() >= 15) {
            // getBankCardName(mCardNumber);
            // }
        }
    };

    private BankDetailsBean bankDetailsBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_bank_add;
    }

    @Override
    protected void initView() {
        mUserName = findViewById(R.id.et_user_name);
        mUserIDCard = findViewById(R.id.et_id_card_number);
        mBankCard = findViewById(R.id.et_bank_card_number);
        mBankCardName = findViewById(R.id.tv_bank_name);
        mBtnSubmit = findViewById(R.id.btn_submit_bank_info);

        // Initialize new fields
        mRecipientPhone = findViewById(R.id.et_recipient_phone);
        layoutRecipientInfo = findViewById(R.id.layout_recipient_info);
        layoutRecipientPhotos = findViewById(R.id.layout_recipient_photos);
        mIvIdCardFront = findViewById(R.id.iv_id_card_front);
        mIvIdCardBack = findViewById(R.id.iv_id_card_back);
        mTvIdCardFrontTips = findViewById(R.id.tv_id_card_front_tips);
        mTvIdCardBackTips = findViewById(R.id.tv_id_card_back_tips);

        layoutBankInfo = findViewById(R.id.layout_card_number);
        layoutCardUserName = findViewById(R.id.layout_card_user_name);
        layoutCardIdCard = findViewById(R.id.layout_card_id_card);

        mSwitchBtn = findViewById(R.id.switch_btn);
        mSwitchBtn.setColor(0xFF3265F9, 0xFF3265F9);

        setOnClickListener(mBtnSubmit);



        InputTextHelper.with(this)
                .addView(mUserName)
                .addView(mUserIDCard)
                .addView(mBankCard)
                .addView(mBankCardName)
                .addView(mRecipientPhone)
                .setMain(mBtnSubmit)
                .build();



        mSwitchBtn.setOnCheckedChangeListener((button, isChecked) -> {
            if (isChecked)
                isDefault = MTLConstants.IS_DEFAULT;
            else
                isDefault = MTLConstants.IS_NOT_DEFAULT;
        });

        mBankCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // if (delayRun != null) {
                // //每次editText有变化的时候，则移除上次发出的延迟线程
                // handler.removeCallbacks(delayRun);
                // }
                //
                // mCardNumber = s.toString();
                //
                // //延迟800ms，如果不再输入字符，则执行该线程的run方法
                // handler.postDelayed(delayRun, 1000);
            }
        });

        mBankCardName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(BankCompanyListActivity.class, new OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode, @Nullable Intent data) {
                        if (RESULT_OK == resultCode && null != data) {
                            dictBean = (DictBean) data.getSerializableExtra("bank");
                            layoutBankInfo.setVisibility(View.VISIBLE);
                            layoutCardUserName.setVisibility(View.VISIBLE);
                            layoutCardIdCard.setVisibility(View.VISIBLE);
                            mBankCardName.setText(null == dictBean ? "" : dictBean.getDictLabel());
                        }
                    }
                });
            }
        });

        mBankCard.setOnEditorActionListener((v, actionId, event) -> {
            // if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // //点击搜索的时候隐藏软键盘
            // //在这里调用服务器的接口，获取数据
            // String mCardNumber = mBankCard.getText().toString().trim();
            // getBankCardName(mCardNumber);
            // // 在这里写搜索的操作,一般都是网络请求数据
            // return true;
            // }
            return false;
        });

        // 设置身份证照片上传点击事件
        mIvIdCardFront.setOnClickListener(v -> {
            mCurrentSelectIndex = 0;
            showTipsDialog();
        });

        mIvIdCardBack.setOnClickListener(v -> {
            mCurrentSelectIndex = 1;
            showTipsDialog();
        });

        // 身份证号输入监听
        mUserIDCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString().trim();
                if (TextUtils.isEmpty(idCard)) {
                    layoutRecipientInfo.setVisibility(View.GONE);
                    layoutRecipientPhotos.setVisibility(View.GONE);
                    return;
                }

                // 验证身份证格式
                if (!RegexUtils.isIDCard18(idCard) && !RegexUtils.isIDCard15(idCard)) {
                    // toast("请输入正确的身份证号");
                    layoutRecipientInfo.setVisibility(View.GONE);
                    layoutRecipientPhotos.setVisibility(View.GONE);
                    return;
                }

                layoutRecipientInfo.setVisibility(View.VISIBLE);
                layoutRecipientPhotos.setVisibility(View.VISIBLE);

                // 比较输入的身份证号是否与用户自己的身份证号一致
                if (!TextUtils.isEmpty(mUserOwnIdCard) && !mUserOwnIdCard.equals(idCard)) {
                    // 不一致，显示额外信息输入区域

                } else {
                    // 一致，隐藏额外信息输入区域
                    UserInfoBean userInfoBean = (UserInfoBean) CommonHelper.getSavedObject("userInfo", UserInfoBean.class);
                    if (!ObjectUtils.isEmpty(userInfoBean)) {
                        mRecipientPhone.setText(ReplaceHelper.phoneFormat(userInfoBean.getPhone()));
                    }

                    if (!TextUtils.isEmpty(mFrontImage)) {
                        ShowImageHelper.showNormal(MyBankEditActivity.this, mFrontImage, mIvIdCardFront);
                        mTvIdCardFrontTips.setVisibility(View.GONE);
                    }
                    if (!TextUtils.isEmpty(mBackImage)) {
                        ShowImageHelper.showNormal(MyBankEditActivity.this, mBackImage, mIvIdCardBack);
                        mTvIdCardBackTips.setVisibility(View.GONE);
                    }
                }



            }
        });

        if (getIntent().hasExtra("bankInfo")) {
            try {
                bankInfoBean = (BankInfoBean) getIntent().getSerializableExtra("bankInfo");
                mUserName.setText(bankInfoBean.getAccountHolder());
                mUserName.setEnabled(false);
                mUserIDCard.setText(bankInfoBean.getIdentityCard());
                mUserIDCard.setEnabled(false);
                mBankCard.setText(bankInfoBean.getBankCard());
                mBankCard.setEnabled(false);
                mBankCardName.setVisibility(View.VISIBLE);
                mBankCardName.setText(bankInfoBean.getBankName());
                mSwitchBtn.setChecked(bankInfoBean.getDefaultState() == 0);
                mSwitchBtn.setEnabled(false);
                layoutBankInfo.setVisibility(View.VISIBLE);
                layoutCardUserName.setVisibility(View.VISIBLE);
                layoutCardIdCard.setVisibility(View.VISIBLE);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void initData() {
        // 获取用户自己的身份证号
        EasyHttp.get(this)
                .api(new GetUserInfoApi())
                .request(new HttpCallback<HttpData<IdCardBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<IdCardBean> data) {
                        mUserOwnIdCard = data.getData().getIdCard();
                        mFrontImage = data.getData().getIdCardFrontUrl();
                        mBackImage = data.getData().getIdCardReverseUrl();

                        // 如果已经输入了身份证号，且与用户自己的身份证号一致，则自动加载身份证图片
                        String inputIdCard = mUserIDCard.getText().toString().trim();
                        if (!TextUtils.isEmpty(inputIdCard) && inputIdCard.equals(mUserOwnIdCard)) {
                            if (!TextUtils.isEmpty(mFrontImage)) {
                                ShowImageHelper.showNormal(MyBankEditActivity.this, mFrontImage, mIvIdCardFront);
                                mTvIdCardFrontTips.setVisibility(View.GONE);
                            }
                            if (!TextUtils.isEmpty(mBackImage)) {
                                ShowImageHelper.showNormal(MyBankEditActivity.this, mBackImage, mIvIdCardBack);
                                mTvIdCardBackTips.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        toast("获取用户信息失败");
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (v == mBtnSubmit) {
            addBankCard();
        }
    }

    private void getBankCardName(String bankNumber, String userName, String idCard) {
        // 获取银行卡信息
        // todo 临时屏蔽银行卡 检测
        // EasyHttp.get(this)
        // .api(new GetBankNameApi().setAuthorization().setBankcard(bankNumber))
        // .request(new HttpCallback<HttpBankData<BankDetailsBean>>(this) {
        //
        // @Override
        // public void onSucceed(HttpBankData<BankDetailsBean> data) {
        // bankDetailsBean = data.getResult();
        // if (dictBean.getDictLabel().contains(bankDetailsBean.getBankName())) {
        // mBankCardName.setText(null == dictBean ? "" : dictBean.getDictLabel());
        //
        // } else {
        // toast("银行卡号与所选银行卡信息不一致");
        // }
        // }
        //
        // @Override
        // public void onFail(Exception e) {
        // toast("请输入正确的银行卡号");
        // }
        // });
        submitInfo(userName, idCard, bankNumber);
    }

    /**
     * 信息提交
     */
    private void submitInfo(String userName, String idCard, String bankNumber) {
        // 检查手机号和身份证号是否为空
        if (TextUtils.isEmpty(idCard)) {
            toast("请输入持卡人身份证号");
            return;
        }
        String recipientPhone = "";
        if(!TextUtils.isEmpty(mUserOwnIdCard) && !mUserOwnIdCard.equals(idCard)){
            // 检查手机号
            recipientPhone = mRecipientPhone.getText().toString().trim();
            if (TextUtils.isEmpty(recipientPhone)) {
                toast("请输入收款人手机号");
                return;
            }

            if (!RegexUtils.isMobileExact(recipientPhone)) {
                toast("请输入正确的手机号");
                return;
            }
        }else {
            // 一致，隐藏额外信息输入区域
            UserInfoBean userInfoBean = (UserInfoBean) CommonHelper.getSavedObject("userInfo", UserInfoBean.class);
            if (!ObjectUtils.isEmpty(userInfoBean)) {
                recipientPhone = userInfoBean.getPhone();
            }

        }

        // 检查身份证照片是否已上传
        if (TextUtils.isEmpty(mFrontImage)) {
            toast("请上传身份证正面照片");
            return;
        }
        if (TextUtils.isEmpty(mBackImage)) {
            toast("请上传身份证反面照片");
            return;
        }

        // 添加银行卡信息
        EasyHttp.put(this)
                .api(new EditBankInfoApi()
                        .setBankCardId(String.valueOf(bankInfoBean.getId()))
                        .setBankId(bankInfoBean.getBankId())
                        .setBankCard(bankNumber)
                        .setCardType(null == bankDetailsBean ? "借记卡" : bankDetailsBean.getCardType())
                        .setAccountHolder(userName)
                        .setIdentityCard(idCard)
                        .setBankName(bankInfoBean.getBankName())
                        .setDefaultState(isDefault)
                        .setRecipientPhone(recipientPhone)
                        .setFrontImage( mFrontImage )
                        .setBackImage( mBackImage )
                        .setIsSelf(!TextUtils.isEmpty(mUserOwnIdCard) && mUserOwnIdCard.equals(idCard) ? 1 : 0))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new BaseDialog.Builder(this)
                .setContentView(R.layout.dialog_certificate_tips)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .setGravity(Gravity.BOTTOM)
                .setOnClickListener(R.id.tv_know, (dialog, view) -> {
                    dialog.dismiss();
                    startImageSelectActivity();
                })
                .show();
    }

    /**
     * 启动图片选择
     */
    private void startImageSelectActivity() {

        ImageSelectVBActivity.start(this, new ImageSelectVBActivity.OnPhotoSelectListener() {
            @Override
            public void onSelected(File file) {
                uploadImage(file);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 上传图片
     */
    private void uploadImage(File file) {
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImage(file))
                .request(new HttpCallback<HttpData<FileBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<FileBean> data) {
                        String imgUrl = data.getData().getUrl();
                        if (mCurrentSelectIndex == 0) {
                            mFrontImage = imgUrl;
                            ShowImageHelper.showNormal(MyBankEditActivity.this, imgUrl, mIvIdCardFront);
                            mTvIdCardFrontTips.setVisibility(View.GONE);
                        } else {
                            mBackImage = imgUrl;
                            ShowImageHelper.showNormal(MyBankEditActivity.this, imgUrl, mIvIdCardBack);
                            mTvIdCardBackTips.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void addBankCard() {
        String userName = mUserName.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            toast("请输入持卡人姓名");
            return;
        }
        String idCard = mUserIDCard.getText().toString().trim();
        if (TextUtils.isEmpty(idCard)) {
            toast("请输入持卡人身份证号");
            return;
        }
        if (!RegexUtils.isIDCard18(idCard) && !RegexUtils.isIDCard15(idCard)) {
            toast("请输入正确的身份证号");
            return;
        }

        String bankNumber = mBankCard.getText().toString().trim();
        if (TextUtils.isEmpty(bankNumber)) {
            toast("请输入银行卡卡号");
            return;
        }
        if (null == dictBean && bankInfoBean == null) {
            toast("请选择银行卡");
            return;
        }
        getBankCardName(bankNumber, userName, idCard);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
    }
}
